/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bs.coregamelibrary.protocoltea.codec.decoder;

import com.bs.coregamelibrary.protocoltea.codec.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.util.List;

/**
 *
 * @author dungpt
 */
public class ProtocolTeaDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext chc, ByteBuf msg, List<Object> list) throws Exception {
        if (msg.isReadable(4)) {
            final byte[] array;
            msg.markReaderIndex();
            int length = msg.readInt();
            if (msg.readableBytes() != length) {
                msg.resetReaderIndex();
                return;
            }
//                msg.readByte();
            if (length >= 1) {
                array = new byte[length - 1];
                msg.getBytes(msg.readerIndex(), array, 0, length);
                ByteArrayInputStream inputStream;
                byte[] messageData;
                inputStream = new ByteArrayInputStream(array);
                DataInputStream dis = new DataInputStream(inputStream);
                int cmdId = dis.readInt();
                int subId = dis.readInt();
                messageData = new byte[dis.available()];
                dis.read(messageData);
                Message message = new Message(cmdId, subId, messageData);
                list.add(message);
                dis.close();
                inputStream.close();
            }
        }
    }

}
